package org.xshaokuang.loginandemail.email;

import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.utils.Config;
import org.xshaokuang.loginandemail.MainPlugin;
import org.xshaokuang.loginandemail.tool.Tool;
import org.xshaokuang.loginandemail.tool.ToolItemBuild;

import java.util.*;
import java.util.stream.Collectors;

public class EmailDataManager {
    private final Map<String, List<EmailData>> emailDataMap = new HashMap<>();
    private final Config config;

    public EmailDataManager() {
        this.config = MainPlugin.getInstance().emailData;
    }

    public boolean hasEmail(Player player) {
        return emailDataMap.containsKey(player.getName().toLowerCase());
    }

    public int unreadEmailNum(Player player) {
        return (int) getPlayerEmails(player.getName().toLowerCase()).stream()
                .filter(email -> email.getFlag() == 0)
                .count();
    }

    public void loadFromConfig(String name) {
        String playerName = name.toLowerCase();
        if (config.exists(playerName)) {
            Object rawData = config.get(playerName);
            if (rawData == null) {
                emailDataMap.remove(playerName);
                return;
            }
            try {
                // 类型转换确保数据格式正确
                List<Map<String, Object>> emailList = (List<Map<String, Object>>) rawData;

                // 流处理转换邮件数据
                List<EmailData> emails = emailList.stream()
                        .map(this::parseEmailData)
                        .filter(Objects::nonNull)
                        .filter(email -> {
                            long expiryTime = email.getTimestamp() +
                                    email.getKeepDays() * 86400L; // 计算过期时间戳
                            return !Tool.isOverTime(expiryTime); // 判断是否未超时
                        })
                        .collect(Collectors.toList());

                // 更新到数据映射表
                emailDataMap.put(playerName, emails);
            } catch (ClassCastException e) {
                // 处理类型不匹配的情况（例如配置数据损坏）
                emailDataMap.remove(playerName);
                System.out.println("玩家邮件数据格式错误：" + playerName);
                // 可选：记录错误日志或抛出异常
            }
        }
    }

    // 从配置文件加载全部数据
    public void loadAllFromConfig() {
        emailDataMap.clear();
        Map<String, Object> rawData = config.getAll();

        for (Map.Entry<String, Object> entry : rawData.entrySet()) {
            String playerName = entry.getKey();
            List<Map<String, Object>> emailList = (List<Map<String, Object>>) entry.getValue();

            List<EmailData> emails = emailList.stream()
                    .map(this::parseEmailData)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            emailDataMap.put(playerName.toLowerCase(), emails);
        }
    }

    public void remove(String playerName) {
        emailDataMap.remove(playerName.toLowerCase());
    }

    public void print(String playerName)  {
        System.out.println("=====EMAILDATA PRINT=====");
        if(emailDataMap.get(playerName.toLowerCase()) != null) {
            for (EmailData email : emailDataMap.get(playerName.toLowerCase())) {
                email.print();
            }
        }
    }

    public void saveToConfig(String name) {
        // 统一使用小写名称作为键
        String key = name.toLowerCase();

        // 获取指定玩家的邮件列表
        List<EmailData> emails = emailDataMap.get(key);

        if (emails == null || emails.isEmpty()) {
            // 如果玩家不存在或邮件列表为空，移除配置文件中的条目
            config.remove(key);
        } else {
            // 序列化邮件数据
            List<Map<String, Object>> serialized = emails.stream()
                    .map(this::serializeEmailData)
                    .collect(Collectors.toList());

            // 更新配置文件中的玩家数据
            config.set(key, serialized);
        }

        // 保存到文件
        config.save();
        remove(key);
    }

    // 保存全部数据到配置文件
    public void saveAllToConfig() {
        // 清空原有配置（可选）
        //config.getAll().keySet().forEach(config::remove);

        // 批量写入新数据
        emailDataMap.forEach((playerName, emails) -> {
            List<Map<String, Object>> serialized = emails.stream()
                    .map(this::serializeEmailData)
                    .collect(Collectors.toList());

            // 使用set方法逐项添加
            config.set(playerName, serialized);
            remove(playerName);
        });

        // 保存到文件
        config.save();
    }

    // 获取玩家邮件
    public List<EmailData> getPlayerEmails(String playerName) {
        return emailDataMap.get(playerName.toLowerCase());
    }

    // 添加新邮件
    public void addEmail(String playerName, EmailData email) {
        String key = playerName.toLowerCase();
        if(emailDataMap != null) {
            emailDataMap.computeIfAbsent(key, k -> new ArrayList<>())
                    .add(email);
        }
    }

    public void addEmailInConfig(String playerName, EmailData email) {
        loadFromConfig(playerName);
        addEmail(playerName, email);
        saveToConfig(playerName);
    }

    // 序列化邮件数据
    private Map<String, Object> serializeEmailData(EmailData email) {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("timestamp", email.getTimestamp());
        data.put("keepDays", email.getKeepDays());
        data.put("text", email.getText());
        data.put("flag", email.getFlag());
        data.put("from", email.getFrom());

        // 使用ToolItemBuild序列化物品
        List<Map<String, Object>> items = email.getItems().stream()
                .map(item -> {
                    Map<String, Object> converted = ToolItemBuild.itemToMap(item);
                    Map c2 = ToolItemBuild.itemToMap(item);
                    return converted;
                })
                .filter(map -> !map.isEmpty())
                .collect(Collectors.toList());

        data.put("items", items);
        return data;
    }

    // 反序列化邮件数据
    private EmailData parseEmailData(Map<String, Object> data) {
        try {
            // 基础字段解析
            long timestamp = ((Number) data.get("timestamp")).longValue();
            int keepDays = ((Number) data.get("keepDays")).intValue();
            String text = (String) data.getOrDefault("text", "");
            int flag = ((Number) data.get("flag")).intValue();
            String from = (String) data.getOrDefault("from", "");

            // 物品反序列化
            List<Map<String, Object>> rawItems =
                    (List<Map<String, Object>>) data.getOrDefault("items", new ArrayList<>());

            List<Item> items = rawItems.stream()
                    .map(map -> ToolItemBuild.mapToItem(new HashMap<>(map))) // 转换为标准Map
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            return new EmailData(timestamp, keepDays, text, items, flag, from);
        } catch (Exception e) {
            System.err.println("邮件数据解析失败: " + data);
            e.printStackTrace();
            return null;
        }
    }
}
